<script setup>
import { useCartStore } from '@/stores/cartStore'
import { useUserStore } from '@/stores/user'
import { onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import http from '@/utils/http'

const cartStore = useCartStore()
const userStore = useUserStore()
const router = useRouter()

defineOptions({
  name: 'CartListPage'
});

// 调试辅助：打印购物车中的所有商品
const logCartItems = () => {
  console.log('购物车页面内容：', cartStore.cartList)
  cartStore.cartList.forEach((item, index) => {
    console.log(`商品 ${index+1}:`, {
      id: item.id,
      skuId: item.skuId,
      name: item.name,
      picture: item.picture,
      price: item.price,
      count: item.count,
      goods: item.goods
    })
  })
}

// 初始加载购物车数据
onMounted(async () => {
  if (userStore.userInfo?.id) {
    try {
      await cartStore.updateNewList()
      console.log('CartList组件中购物车数据加载完成')
      logCartItems()
    } catch (error) {
      ElMessage.error('获取购物车数据失败')
      console.error('获取购物车数据失败:', error)
    }
  } else {
    console.log('用户未登录，显示本地购物车数据')
    logCartItems()
  }
})

// 判断图片路径是否有效，如果无效则使用默认图片
const getValidImageUrl = (item) => {
  if (!item) return 'https://via.placeholder.com/100'
  
  const imgUrl = item.picture || (item.goods?.image)
  return imgUrl || 'https://via.placeholder.com/100'
}

// 获取商品名称
const getItemName = (item) => {
  if (!item) return '未知商品'
  return item.name || (item.goods?.name) || '未命名商品'
}

// 获取商品价格
const getItemPrice = (item) => {
  if (!item) return 0
  return item.price || (item.goods?.price) || 0
}

const singleCheck = (i,selected) => {
  console.log(i,selected)
  cartStore.singleCheck(i.skuId,selected)
}

const allCheck = (selected) => {
  cartStore.allCheck(selected)
}

// 结算跳转
const goCheckout = () => {
  // 判断是否登录
  if (!userStore.userInfo?.id) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }
  
  // 判断是否有选中的商品
  if (cartStore.selectedCount === 0) {
    ElMessage.warning('请至少选择一件商品')
    return
  }
  
  // 跳转到结算页
  router.push('/checkout')
}

// 强制选中所有商品（调试用）
const forceSelectAll = async () => {
  const userId = userStore.userInfo?.id
  if (!userId) {
    ElMessage.warning('请先登录')
    return
  }
  
  try {
    // 调用后端API直接更新数据库
    await http({
      url: '/member/cart/checkAll',
      method: 'POST',
      data: { selected: true },
      params: { userId }
    })
    
    ElMessage.success('已强制选中所有商品')
    // 刷新购物车数据
    await cartStore.updateNewList()
  } catch (error) {
    console.error('强制选中所有商品失败', error)
    ElMessage.error('操作失败：' + (error.response?.data || error.message))
  }
}
</script>

<template>
  <div class="xtx-cart-page">
    <div class="container m-top-20">
      <div class="cart">
        <table>
          <thead>
            <tr>
              <th width="120">
                <el-checkbox :model-value="cartStore.isAll" @change="allCheck" />
              </th>
              <th width="400">商品信息</th>
              <th width="220">单价</th>
              <th width="180">数量</th>
              <th width="180">小计</th>
              <th width="140">操作</th>
            </tr>
          </thead>
          <!-- 商品列表 -->
          <tbody>
            <tr v-for="(item, index) in cartStore.cartList" :key="index">
              <td>
                <el-checkbox :model-value="item.selected" @change="(selected) => singleCheck(item, selected)" />
              </td>
              <td>
                <div class="goods">
                  <RouterLink to="/"><img :src="getValidImageUrl(item)" alt="商品图片" /></RouterLink>
                  <div>
                    <p class="name ellipsis">
                      {{ getItemName(item) }}
                    </p>
                  </div>
                </div>
              </td>
              <td class="tc">
                <p>&yen;{{ getItemPrice(item) }}</p>
              </td>
              <td class="tc">
                <el-input-number v-model="item.count" :min="1" />
              </td>
              <td class="tc">
                <p class="f16 red">&yen;{{ (getItemPrice(item) * (item.count || 1)).toFixed(2) }}</p>
              </td>
              <td class="tc">
                <p>
                  <el-popconfirm title="确认删除吗?" confirm-button-text="确认" cancel-button-text="取消" @confirm="cartStore.delCart(item.skuId)">">
                    <template #reference>
                      <a href="javascript:;">删除</a>
                    </template>
                  </el-popconfirm>
                </p>
              </td>
            </tr>
            <tr v-if="cartStore.cartList.length === 0">
              <td colspan="6">
                <div class="cart-none">
                  <el-empty description="购物车列表为空">
                    <el-button type="primary">随便逛逛</el-button>
                  </el-empty>
                </div>
              </td>
            </tr>
          </tbody>

        </table>
      </div>
      <!-- 操作栏 -->
      <div class="action">
        <div class="batch">
          共 {{ cartStore.allCount }} 件商品，已选择 {{ cartStore.selectedCount }} 件，商品合计：
          <span class="red">¥ {{ cartStore.selectedPrice.toFixed(2) }} </span>
          <el-button size="small" type="info" @click="forceSelectAll" style="margin-left: 10px;">强制选中所有商品</el-button>
        </div>
        <div class="total">
          <el-button size="large" type="primary" @click="goCheckout">下单结算</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.xtx-cart-page {
  margin-top: 20px;

  .cart {
    background: #fff;
    color: #666;

    table {
      border-spacing: 0;
      border-collapse: collapse;
      line-height: 24px;

      th,
      td {
        padding: 10px;
        border-bottom: 1px solid #f5f5f5;

        &:first-child {
          text-align: left;
          padding-left: 30px;
          color: #999;
        }
      }

      th {
        font-size: 16px;
        font-weight: normal;
        line-height: 50px;
      }
    }
  }

  .cart-none {
    text-align: center;
    padding: 120px 0;
    background: #fff;

    p {
      color: #999;
      padding: 20px 0;
    }
  }

  .tc {
    text-align: center;

    a {
      color: $xtxColor;
    }

    .xtx-numbox {
      margin: 0 auto;
      width: 120px;
    }
  }

  .red {
    color: $priceColor;
  }

  .green {
    color: $xtxColor;
  }

  .f16 {
    font-size: 16px;
  }

  .goods {
    display: flex;
    align-items: center;

    img {
      width: 100px;
      height: 100px;
      object-fit: cover;
    }

    >div {
      width: 280px;
      font-size: 16px;
      padding-left: 10px;

      .attr {
        font-size: 14px;
        color: #999;
      }
    }
  }

  .action {
    display: flex;
    background: #fff;
    margin-top: 20px;
    height: 80px;
    align-items: center;
    font-size: 16px;
    justify-content: space-between;
    padding: 0 30px;

    .xtx-checkbox {
      color: #999;
    }

    .batch {
      a {
        margin-left: 20px;
      }
    }

    .red {
      font-size: 18px;
      margin-right: 20px;
      font-weight: bold;
    }
  }

  .tit {
    color: #666;
    font-size: 16px;
    font-weight: normal;
    line-height: 50px;
  }

}
</style>
